<?php
namespace Admin\Controller;
use Think\Controller;
class ProductController extends CommonController{
	public function lists()
	{
		if(IS_GET){
			
			$User=M('product');
			/**
			数据分页显示开始
			**/
                        $map_search['isfood']=1;
                        
                        $if_testreport = I("get.if_testreport");
                        if($if_testreport==1)
                        {
                           $map_search['if_testreport']=0; 
                        }
                        
                        
			$count      = $User->where($map_search)->count();// 查询满足要求的总记录数
//                        print_r($User->getLastSql());
//                        exit();
			$Page       = new \Think\Page($count,40);// 实例化分页类 传入总记录数和每页显示的记录数(25)
			$Page->lastSuffix=false;
                        $Page->setConfig('header','<li class="rows">共<b>'.$count.'</b>条记录&nbsp;&nbsp;每页<b>40</b>条&nbsp;&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
                        $Page->setConfig('prev','上一页');
                        $Page->setConfig('next','下一页');
                        $Page->setConfig('last','末页');
                        $Page->setConfig('first','首页');
                        $Page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
			$show       = $Page->show();// 分页显示输出
			// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
			$list = $User->where($map_search)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
			/**j
			数据分页结束upload_third_party
			**/


			//查询产品对应的分类
			foreach ($list as $k => $v) 
			{
				$map['id']=$v['classify'];
				$list[$k]['classify']=M('food_classify')->where($map)->getField('name');
			}

			// print_r($list); die;
			$this->assign('list',$list);
			$this->assign('page',$show);
			$this->display();
		}else if(IS_POST){

			/**
			 * 搜索
			 */
			$product_name = trim(I('post.product_name'));
			
			if(!empty($product_name)){
				$product_name = '%'.$product_name.'%';
				$map2['name'] = array('like',$product_name);
			}

			$barcode = trim(I('post.barcode'));
			
			if(!empty($barcode)){
				$map2['barcode'] = $barcode;
			}
                        
//                        $machine_match_count = trim(I('post.machine_match_count'));
//                        $manual_macth_count = trim(I('post.manual_macth_count'));
                        
//                        if(empty($machine_match_count))
//                        {
//                            echo $machine_match_count;
//                            if($machine_match_count==0)
//                            {
//                                $map2['machine_match_count']  = $machine_match_count;
//                            }
//                        }
//                        else
//                        {
//                           $map2['machine_match_count']  = $machine_match_count;
//                        }
//                        
//                        if(empty($manual_macth_count))
//                        {
//                            if($manual_macth_count==0)
//                            {
//                                $map2['manual_macth_count']  = $manual_macth_count;
//                            }
//                        }
//                        else
//                        {
//                           $map2['manual_macth_count']  = $manual_macth_count;
//                        }


			$DB = M('product');
			$list = $DB->where($map2)->select();
//			 echo $DB->getLastsql(); die;
			//查询产品对应的分类
			foreach ($list as $k => $v) {

				$map['id']=$v['classify'];
				$list[$k]['classify']=M('food_classify')->where($map)->getField('name');
			}

			$this->assign('list',$list);
			$this->display();
		}
	}

        
        /*
         * 计算产品和 第三方食药局数据的关联
         */
        public function product2third_part_product() {
            if(IS_POST)
            {
                $DB = M("product_and_thirdparty_relationship");
                $pid = I("post.pid");
                $thirdid = I("post.thirdid");
                
                $product = M("product")->find($pid);
                
                $compare_data = $DB->where(array('pid'=>$pid))->select();
                
                
                foreach ($thirdid as $key => $value) {
                    /*
                     * 插入不一样的到表去
                     */
                    $this->_chk_product2third_part_product_relationship($pid, $value,$product);
                }
                
                /*
                 * 实时更新统计数据
                 */
                $this->_update_realtime_stat($pid);
                
                $this->success("修改成功");
                
                
            }
            else
            {
                $pid = I("get.id");
                /*
                 * 获取产品信息
                 * 
                 */
                $product = M("product")->find($pid);
                
                if(empty($product['classify_name']) || empty($product['brand']))
                {
                    $this->error("产品信息(分类/品牌)尚未完善");
                    exit();
                }
                
                /*
                 * 获取已经匹配好的数据
                 */
                $match_data = M("product_and_thirdparty_relationship")->where(array('pid'=>$pid))->select();
                
                foreach ($match_data as $key => $value) {
                    $match_data[$key]['thirdparty'] = M("third_party_product")->find($value['thirdid']);
                }
                
                /*
                 * 获取动态计算得到的第三方信息
                 */
                $map['b_category'] = $product['classify_name'];
                $map['brand']=$product['brand'];
                
                
                
                $res = M("third_party_product")->where($map)->select();
                
                
                
//                print_r(M("third_party_product")->getLastSql());
////                
                
                $this->assign("sql_str",M("third_party_product")->getLastSql());
                $this->assign("product", $product);
                $this->assign("match_data", $match_data);
                $this->assign("results", $res);
                
                $this->display(); 
            }
            
        }
        
        /*
         * 检查绑定关系是否已经存在
         */
        public function _chk_product2third_part_product_relationship($pid,$thirdid,$product) {
            $map['pid']=$pid;
            $map['thirdid']=$thirdid;
                   
            $DB = M("product_and_thirdparty_relationship");
           $res = $DB->where($map)->select();
           
           if(!empty($res))
           {
               
           }
           else
           {
               $data['pid']=$pid;
               $data['thirdid']=$thirdid;
               $data['ctime']=I("server.REQUEST_TIME");
               
               $id = $DB->add($data);
               
               if($id)
               {

                   //先备份名字
                   $this->_backup_thirdparty_name($thirdid);
                   
                   //第三方也改名字
                   $DB2 = M("third_party_product");
                   
                   $DB2->id = $thirdid;
                   $DB2->product_name = $product['name'];
                   $DB2->short_product_name = $product['shortname'];
                   $DB2->barcode = $product['barcode'];
                   $DB2->save();
                   
               }
               
           }
            
        }
        
        /*
         * 跑一遍,保存第三方数据产品的新旧名字
         */
        public function _backup_thirdparty_name($thirdid) {
            $DB2 = M("third_party_product");
            $res = $DB2->find($thirdid);
            
            $DB2->id = $thirdid;
            $DB2->product_name_old=$res['product_name'];
            
            $DB2->save();
            
            
            
        }
        /*
         * 实时更新统计数据
         */
        public function _update_realtime_stat($pid) {
            $DB = M("product_and_thirdparty_relationship");
            $map['pid']= $pid;
            
            $res_count = $DB->where($map)->count();
            
            $DB_p = M("product");
            $DB_p->id = $pid;
            $DB_p->manual_macth_count = $res_count;
            $DB_p->save();
        }
        
        /*
         * 取消关联第三方食药局数据
         */
        public function product2third_part_product_del() {
            $id = I("get.id");
            $res = M("product_and_thirdparty_relationship")->find($id);
            
            if(M("product_and_thirdparty_relationship")->delete($id))
            {
                //恢复之前的名字
                $db_thirdparty = M("third_party_product");
                $res_thirdparty =  M("third_party_product")->find($res['thirdid']);
                
                $db_thirdparty->id = $res['thirdid'];
                $db_thirdparty->product_name = $res_thirdparty['product_name_old'];
                
                $db_thirdparty->save();
                
//                echo $db_thirdparty->getLastSql();
//                
//                exit();
                $this->success("取消绑定成功");
            }
            
        }


	/**
	 * 第三方食药局数据列表
	 */
	public function third_part_product(){

		if(IS_GET){

			$User=M('third_party_product');
			/**
			数据分页显示开始
			**/
			$count      = $User->count();// 查询满足要求的总记录数
			$Page       = new \Think\Page($count,40);// 实例化分页类 传入总记录数和每页显示的记录数(25)
			$Page->lastSuffix=false;
		    $Page->setConfig('header','<li class="rows">共<b>%TOTAL_ROW%</b>条记录&nbsp;&nbsp;每页<b>40</b>条&nbsp;&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
		    $Page->setConfig('prev','上一页');
		    $Page->setConfig('next','下一页');
		    $Page->setConfig('last','末页');
		    $Page->setConfig('first','首页');
		    $Page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
			$show       = $Page->show();// 分页显示输出
			// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
			$list = $User->field('id,product_name,b_category,brand,import_remark')->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
			/**j
			数据分页结束upload_third_party
			**/

			// print_r($list); die;
			$this->assign('list',$list);
			$this->assign('page',$show);
			$this->display();
		}
	}
        
        /*
         * 添加食药局数据
         */
        public function third_part_product_add() {
            if(IS_POST)
            {
                $DB = M("third_party_product");
                
                $data['control_no'] = trim(I("post.control_no"));
                $data['firm_name'] = trim(I("post.firm_name"));
                $data['firm_address'] = trim(I("post.firm_address"));
                $data['department_name'] = trim(I("post.department_name"));
                $data['location'] = trim(I("post.location"));
                $data['province'] = trim(I("post.province"));
                $data['city'] = trim(I("post.city"));
                $data['product_name'] = trim(I("post.product_name"));
                $data['short_product_name'] = trim(I("post.short_product_name"));
//                $data['s_category'] = trim(I("post.s_category"));
                $data['s_category'] = trim(I("post.b_category"));
                $data['b_category'] = trim(I("post.b_category"));
                $data['product_type'] = trim(I("post.product_type"));
                $data['product_model'] = trim(I("post.product_model"));
                $data['brand'] = trim(I("post.brand"));
                $data['cdate'] = trim(I("post.cdate"));
                $data['qualified'] = trim(I("post.qualified"));
                $data['item_name'] = trim(I("post.item_name"));
                $data['item_category'] = trim(I("post.item_category"));
                $data['items'] = trim(I("post.items"));
                $data['check_result'] = trim(I("post.check_result"));
                $data['standard'] = trim(I("post.standard"));
                $data['barcode'] = trim(I("post.barcode"));
                $data['bulletin_code_num'] = trim(I("post.bulletin_code_num"));
                $data['bulletin_code'] = trim(I("post.bulletin_code"));
                $data['check_items'] = trim(I("post.check_items"));
                $data['batch_no'] = trim(I("post.batch_no"));
                $data['origin'] = trim(I("post.origin"));
                $data['institution'] = trim(I("post.institution"));
                $data['remark'] = trim(I("post.remark"));
                $data['import_remark'] = trim(I("post.import_remark"));
                $data['ctime'] = I("server.REQUEST_TIME");
                
                
                $id =$DB->add($data);
                
                if($id)
                {
                    $this->success("添加成功");
                }
                else
                {
                    $this->error("添加失败");
                }
                
                
            }
            else {
                $this->assign("import_remark", I("server.REQUEST_TIME"));
                $this->display();
            }
        }
        
        /*
         * 删除食药局数据
         */
        public function third_part_product_del()
        {
            $id = I("get.id");
            
            $DB = M("third_party_product");
            
            if($DB->delete($id))
            {
                $this->success("删除成功");
            }
        }

        /**
	 * ajax修改产品状态
	 */
	public function modify_product_isfood(){

		if(IS_AJAX){

			$isfood = I('post.isfood');
			$data['isfood'] = $isfood;
			$map['id'] = I('post.pid');
			$DB = M('product');

			$re = $DB->where($map)->data($data)->save();

			if($re){

				echo json_encode(1);
			}else{

				echo json_encode(0);
			}
		}
	}



	//添加产品
	public function add_product()
	{
		if(IS_POST)
		{
			$name=trim(I('post.name'));
			$shortname = trim(I('post.shortname'));
			$brand=trim(I('post.brand'));
			$classify_son=I('post.classify_son');
			$barcode=trim(I('post.barcode'));
			$remark=trim(I('post.remark'));
			$data['isthirdparty'] = I('post.isthirdparty');
			// echo $classify_son; die;
			$specification = trim(I('post.specification'));
			if(!empty($specification)){

				$data['specification'] = $specification;
			}
			if(!empty($name))
			{
				$data['name']=$name;
			}
			if(!empty($shortname))
			{
				$data['shortname']=$shortname;
			}
			if(!empty($brand))
			{
				$data['brand']=$brand;
			}
			if(!empty($classify_son))
			{
				$data['classify']=$classify_son;
			}
			if(!empty($barcode))
			{
				$data['barcode']=$barcode;
			}
			if(!empty($remark))
			{
				$data['remark']=$remark;
			}
			// print_r($_FILES); die;
			if(!empty($_FILES['product_img']['size'])){

				$data['imgurl'] =__ROOT__.'/Uploads/'.$this->upload();
				// echo $data['imgurl']; die;
			}

			$data['ctime']=I('server.REQUEST_TIME');
			$User=M('product');
			$re=$User->data($data)->add();
			if($re)
			{
				$this->success('添加成功!',U('Admin/Product/lists'));
			}
			else
			{
				$this->error('添加失败!');
			}

		}
		else
		{
			$level_one[]='>产品管理';
			$level_one[]="";
			$level_two[]='>产品列表';
			$level_two[]=U('Admin/Product/lists');
			$level_three[]='>添加产品';
			$level_three[]=U('Admin/Product/add_product');
			$this->assign('level_one',$level_one);
			$this->assign('level_two',$level_two);
			$this->assign('level_three',$level_three);

			///////////////////////////////////////////////////////////////////
			$User=M('food_classify');
			$map['pid']=0;
			$map['state']=1;
			$list=$User->where($map)->select();
			$this->assign('list',$list);
			$this->display('add_product');
		}
		
	}

	//文件上传累
	public function upload()
	{
		$upload = new \Think\Upload();// 实例化上传类
		$upload->maxSize   =     5242880 ;// 设置附件上传大小
		$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
		$upload->savePath  =      'product/original/'; // 设置附件上传目录
		// 上传文件 
		$info   =   $upload->uploadOne($_FILES['product_img']);
		if(!$info)
		{
		// 上传错误提示错误信息    
			$this->error($upload->getError());
		}
		else
		{
			// 上传成功 获取上传文件信息    
			return $info['savepath'].$info['savename'];    
		}
	}

	// 图像等比例缩小裁剪
	// public function img_thumb1($img_url)
	// {
	// 	$image = new \Think\Image(); 
	// 	$img_url = './'.$img_url;
	// 	$image->open("$img_url");
	// 	$img_name=$this->img_name().'.jpg';
	// 	$re_small_url=__ROOT__.'/'.'Uploads'.'/'.'product'.'/'.'change_small'.'/'.$img_name;
	// 	$small_url='./'.'Uploads'.'/'.'product'.'/'.'change_small'.'/'.$img_name;
	// 	// echo $small_url; die;
	// 	// 生成一个居中裁剪为30*30的缩略图并保存
	// 	$image->thumb(50, 50,\Think\Image::IMAGE_THUMB_FILLED)->save($small_url);
	// 	return $re_small_url;
	// }

	//删除产品
	public function del_product()
	{
		$id=I('post.id');

		if(!empty($id))
		{
			$map['id']=$id;
		}
		$User=M('product');
		$re=$User->where($map)->delete();

		if($re)
		{

			echo json_encode(1);
		}
	}


	//修改产品信息
	public function update_product()
	{
		if(IS_POST)
		{
			$id=I('post.id');
			$name=I('post.name');
			$brand=I('post.brand');
			$classify_son=I('post.classify_son');
			$barcode=I('post.barcode');
			$remark=I('post.remark');
			// echo $classify_son; die;


			if(!empty($name))
			{
				$map['id']=$id;
			}
			if(!empty($name))
			{
				$data['name']=$name;
			}
			if(!empty($brand))
			{
				$data['brand']=$brand;
			}
			if(!empty($classify_son))
			{
				$data['classify']=$classify_son;
			}
			if(!empty($barcode))
			{
				$data['barcode']=$barcode;
			}
			if(!empty($remark))
			{
				$data['remark']=$remark;
			}

			// print_r($_FILES); die;
			if(!empty($_FILES['product_img']['size'])){


				$data['imgurl'] =__ROOT__.'/Uploads/'.$this->upload();
				// echo $data['imgurl']; die;
			}

			$User=M('product');
			$re=$User->where($map)->data($data)->save();
			if($re)
			{
				$this->success('修改成功!',U('Admin/Product/lists'));
			}
			else
			{
				$this->error('修改失败!');
			}

		}
		else
		{
			$id=I('get.id');

			if(!empty($id))
			{
				$map['id']=$id;
			}

			$list=M('product')->where($map)->select();
			// print_r($list); die;

			$User_2=M('food_classify');
			foreach ($list as $k => $v) 
			{
				$map['id']=$v['classify'];
				$list[$k]['classify']=$User_2->where($map)->find();
				$mas['id']=$list[$k]['classify']['pid'];
				$list[$k]['f_classify']=$User_2->where($mas)->getField('name');
			}

			$gap['pid']=0;
			$gap['state']=1;
			$lists=M('food_classify')->where($gap)->select();


			$this->assign('list',$list);
			$this->assign('lists',$lists);


			$this->display('update_product');
		}
	}


	/**
	 * 本页面弹出层修改产品
	 */
	public function modify_product(){

		if(IS_POST){
			$map['id'] = I('post.product_id');
			$name=trim(I('post.name'));
			$shortname = trim(I('post.shortname'));
			$brand=trim(I('post.brand'));
			// $classify_son=I('post.classify_son');
			$barcode=trim(I('post.barcode'));
			$remark=trim(I('post.remark'));
			$data['isthirdparty'] = I('post.isthirdparty');
			$classify_name = trim(I('post.classify_name'));
			$classify_id = I('post.classify_id');
			$specification  = trim(I('post.specification'));

			if(!empty($classify_name)){

				// $classifyArray = $this->get_classify_info($classify_name);
				$data['classify'] = $classify_id;
				$data['classify_name'] = $classify_name;
			}
			if(!empty($specification))
			{
				$data['specification']=$specification;
			}
			if(!empty($name))
			{
				$data['name']=$name;
			}
			if(!empty($shortname))
			{
				$data['shortname']=$shortname;
			}
			if(!empty($brand))
			{
				$data['brand']=$brand;
			}else{

				$data['brand'] = '';
			}
			if(!empty($barcode))
			{
				$data['barcode']=$barcode;
			}
			if(!empty($remark))
			{
				$data['remark']=$remark;
			}
			// print_r($_FILES); die;
			if(!empty($_FILES['product_img']['size'])){

				$data['imgurl'] =__ROOT__.'/Uploads/'.$this->upload();
				// echo $data['imgurl']; die;
			}

			$data['ctime']=I('server.REQUEST_TIME');
			$User=M('product');
			$re=$User->where($map)->data($data)->save();
			if($re)
			{
				// $this->redirect();
				$this->success('修改成功');
			}
		}
	}

	//产品分类管理->分类列表
	public function classify_lists()
	{
		if(IS_GET)
		{
			$User=M('food_classify');
			$map['state']=1;
			$map['pid']=0;
			$list=$User->where($map)->select();
			foreach ($list as $k => $v) 
			{
				if($v['state']==1)
				{
					$list[$k]['state']='显示';
				}
				else
				{
					$list[$k]['state']='隐藏';
				}
			}
			// print_r($list); die;
			$this->assign('list',$list);
			$this->display('classify_lists');
		}
	}

	//添加主分类
	public function add_classify()
	{
		if(IS_POST)
		{
			$name=I('post.name');
			$state=I('post.state');
			$name_tag = trim(I('post.name_tag'));
			if(!empty($name_tag)){

				$data['name_tag'] = $name_tag;
			}
			if(!empty($name))
			{
				$data['name']=$name;
			}else{
				$this->error('分类名不能为空!','',1);
			}
			if(isset($state))
			{
				$data['state']=$state;
			}

			if(!empty($_FILES['classify_img']['name'])){

				$data['thumb'] = __ROOT__.'/Uploads'.'/'.$this->classify_upload($_FILES['classify_img']);

			}
			$data['pid']=0;
			$User=M('food_classify');
			if($User->data($data)->add())
			{
				$this->success('添加成功！',U('Admin/Product/classify_lists'));
			}
			else
			{
				$this->error('添加失败！');
			}
		}
		else
		{
			$this->display('add_classify');
		}

		
	}


	//主分类图片上传
	private function classify_upload($file){    
		$upload = new \Think\Upload();// 实例化上传类    
		$upload->maxSize   =     3145728 ;// 设置附件上传大小    
		$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型    
		$upload->savePath  =      'product/classify/'; // 设置附件上传目录    // 上传单个文件     
		$info   =   $upload->uploadOne($file);    
		if(!$info) {
		// 上传错误提示错误信息        
			$this->error($upload->getError());    
		}else{
		// 上传成功 获取上传文件信息         
			return $info['savepath'].$info['savename'];    
		}
	}



	//添加子分类
	public function add_son_classify()
	{
		if(IS_POST) 
		{
			$id=I('post.id');
			$name=I('post.name');
			$state=I('post.state');
			$name_tag = trim(I('post.name_tag'));
			if(!empty($name_tag)){

				$data['name_tag'] = $name_tag;
			}
			if(!empty($id))
			{
				$data['pid']=$id;
			}
			if(!empty($name))
			{
				$data['name']=$name;
			}
			if(isset($state))
			{
				$data['state']=$state;
			}
			$re=M('food_classify')->data($data)->add();
			if($re)
			{
				$this->success('添加成功！');
			}
		}
		else
		{
			$level_one[]='>分类管理';
			$level_one[]="";
			$level_two[]='>分类列表';
			$level_two[]=U('Admin/Product/classify_lists');
			$level_three[]='>添加子分类';
			$level_three[]=U('Admin/Product/add_son_classify');
			$this->assign('level_one',$level_one);
			$this->assign('level_two',$level_two);
			$this->assign('level_three',$level_three);
			$id=I('get.id');
			if(!empty($id))
			{
				$map['id']=$id;
			}
			$list=M('food_classify')->where($map)->find();
			$this->assign('list',$list);
			$this->display('add_son_classify');
		}
	}

	//删除主分类
	public function del_classify()
	{
		if(IS_AJAX)
		{
			$id=I('post.id');
			if(!empty($id))
			{
				$map['id']=$id;
			}
			$User=M('food_classify');
			$re=$User->where($map)->delete();
			if($re)
			{
				echo json_encode(1);
			}

		}
	}

	//修改主分类
	public function update_classify()
	{
		if(IS_POST){
			$id=I('post.id');
			$name=I('post.name');
			$state=I('post.state');
			$name_tag = trim(I('post.name_tag'));
			if(!empty($name_tag)){
				$data['name_tag'] = $name_tag;
			}
			if(!empty($name))
			{
				$data['name']=$name;
			}else{

				$this->error('分类名不能为空!','',1);
			}
			if(isset($state))
			{
				$data['state']=$state;
			}
			if(!empty($id))
			{
				$map['id']=$id;
			}else{

				$this->error('参数出错!','',1);
			}
			// print_r($_FILES); die;
			if(!empty($_FILES['classify_img']['name'])){

				$data['thumb'] = __ROOT__.'/Uploads'.'/'.$this->classify_upload($_FILES['classify_img']);

			}

			// print_r($data); die;
			$re=M('food_classify')->where($map)->data($data)->save();
			if($re)
			{
				$this->success('修改成功！',U('Admin/Product/classify_lists'));
			}
			else
			{
				$this->error('修改失败!','',1);
			}
		}
		else
		{
			$level_one[]='>产品管理';
			$level_one[]="";
			$level_two[]='>分类列表';
			$level_two[]=U('Admin/Product/classify_lists');
			$level_three[]='>修改分类';
			$level_three[]=U('Admin/Product/update_classify');
			$this->assign('level_one',$level_one);
			$this->assign('level_two',$level_two);
			$this->assign('level_three',$level_three);
			$id=I('get.id');
			if(!empty($id))
			{
				$map['id']=$id;
			}
			$list=M('food_classify')->where($map)->find();
			$this->assign('list',$list);
			$this->display('update_classify');
		}
	}

	//查看主分类所属的子分类
	public function classify_lists_son()
	{
		if(IS_GET)
		{
			$id=I('get.id');
			$fname=I('get.name');
			if(!empty($id))
			{
				$map['pid']=$id;
			}
			$User=M('food_classify');
			$map['state']=1;
			$list=$User->where($map)->select();
			foreach ($list as $k => $v) 
			{
				if($v['state']==1)
				{
					$list[$k]['state']='显示';
				}
				else
				{
					$list[$k]['state']='隐藏';
				}
			}
			$this->assign('fid',$id);
			$this->assign('fname',$fname);
			$this->assign('list',$list);
			$this->display('classify_lists_son');
		}
		
	}

	//删除子分类
	public function del_classify_son()
	{
		if(IS_AJAX)
		{
			$id=I('post.id');
			if(!empty($id))
			{
				$map['id']=$id;
			}
			$User=M('food_classify');
			$re=$User->where($map)->delete();
			if($re)
			{
				echo json_encode(1);
			}

		}
	}

	//修改子分类
	public function update_classify_son()
	{
		if(IS_POST)
		{
			$id=I('post.id');
			$name=I('post.name');
			$state=I('post.state');
			$name_tag = trim(I('post.name_tag'));
			$fid = I('post.fid');
			if(!empty($name_tag)){

				$data['name_tag'] = $name_tag;
			}
			if(!empty($name))
			{
				$data['name']=$name;
			}
			if(isset($state))
			{
				$data['state']=$state;
			}
			if(!empty($id))
			{
				$map['id']=$id;
			}
			$re=M('food_classify')->where($map)->data($data)->save();
			if($re)
			{
				$this->success('修改成功!',U('Admin/Product/classify_lists_son',array('id' => $fid)),1);
			}
			else
			{
				$this->error('修改失败!','',1);
			}
		}
		else
		{
			$id=I('get.id');
			$fid = I('get.fid');
			if(!empty($id))
			{
				$map['id']=$id;
			}
			$list=M('food_classify')->where($map)->find();
			$this->assign('fid',$fid);
			$this->assign('list',$list);
			$this->display('update_classify_son');
		}
	}


	//ajax获取对应的二级目录
	public function ready_classify()
	{
		$map['pid']=I('post.id');
		$User=M('food_classify');
		$list=$User->where($map)->select();
		echo json_encode($list);
	}



	//修改添加分类所包含的检测套餐
	public function set_package(){

		if(IS_GET){
			//取出所有的检测项目
			$DB_package = M('fundings_package');
			$package_lists = $DB_package->select();

			//取出该分类已选择的项目
			
			$classify_id = I('get.id');
			if(!empty($classify_id)){
				$map['classify_id'] = $classify_id;
				$this->assign('classify_id',$classify_id);
			}else{

				$this->error('id参数错误!','',1);
			}
			$DB_classify_package_relationship = M('classify_package_relationship');
			$package_id = $DB_classify_package_relationship->where($map)->getField('package_id',true);
			//检测该分类所包含的套餐
			foreach ($package_lists as $k => $v) {
				# code...
				if(in_array($v['id'], $package_id)){

					$package_lists[$k]['checked'] = 1;
				}
			}

			$classify_name = I('get.sname');
			// echo $classify_name;die;
			if(!empty($classify_name)){

				$this->assign('classify_name',$classify_name);
			}else{

				$this->error('name参数错误!','',1);
			}
			// print_r($package_lists); die;
			$this->assign('package_lists',$package_lists);
			$this->display();
		}else if(IS_POST){

			$classify_id_p = I('post.classify_id');
			if(!empty($classify_id_p)){

				$classify_id = $classify_id_p;
			}else{

				$this->error('参数错误!','',1);
			}

			$package_id = I('post.package_id');
			if(!empty($package_id)){

				foreach ($package_id as $k => $v) {
					# code...
					$data[] = array('classify_id' => $classify_id,'package_id' => $v,'ctime' => I('server.REQUEST_TIME'));
				}
			}
			// print_r($data);
			$DB = M('classify_package_relationship');
			//插入数据前先对之前数据进行清理更新
			$DB->where(array('classify_id' => $classify_id))->delete();
			$result = $DB->addAll($data);
			// var_dump($result); die;
			if(!empty($result)){

				$this->success('设置成功!',U('Admin/Product/classify_lists'),1);
			}else{

				$this->error('设置失败!','',1);
			}
		}
	}



	/**
	 * 通过汉字获取对应的分类id
	 */
	private function get_classify_info($classify_name){

		$DB = M('food_classify');
		$classify_name = '%'.$classify_name.'%';
		$map['name'] = array('like',$classify_name);

		$classifyArray = $DB->where($map)->find();

		return $classifyArray;
	}


	/**
	 * 添加孙分类
	 */
	public function add_classify_grandson(){

		if(IS_GET){

			$id = I('get.id');
			$fid = I('get.fid');
			$fname = I('get.fname');

			$this->assign('fname',$fname);
			$this->assign('id',$id);
			$this->assign('fid',$fid);
			$this->display();
		}else{

			$id=I('post.id');
			$fid = I('post.fid');
			$name=I('post.name');
			$state=I('post.state');
			$name_tag = trim(I('post.name_tag'));
			$choose_html_text = I('post.choose_html_text');
			$faq_html_text = I('post.faq_html_text');
			if(!empty($name_tag)){

				$data['name_tag'] = $name_tag;
			}
			if(!empty($id))
			{
				$data['pid']=$id;
			}
			if(!empty($name))
			{
				$data['name']=$name;
			}
			if(isset($state))
			{
				$data['state']=$state;
			}
			if(!empty($choose_html_text)){
				$data['choose_html_text'] = $choose_html_text;
			}
			if(!empty($faq_html_text)){

				$data['faq_html_text'] = $faq_html_text;
			}
			$re=M('food_classify')->data($data)->add();
			if($re)
			{
				$this->success('添加成功!',U('Admin/Product/classify_lists_son',array('id' => $fid)),1);
			}
		}
	}



	/**
	 * 三级分类表
	 */
	public function classify_lists_grandson(){

		if(IS_GET){

			$map['pid'] = I('get.id');
			$fid = I('get.fid');
			$fname = I('get.fname');
			$DB = m('food_classify');

			$list = $DB->where($map)->select();

			$this->assign('list',$list);
			$this->assign('fid',$map['pid']);
			$this->assign('fname',$fname);
			$this->display();
		}
	}


	/**
	 * 修改三级分类
	 */
	public function modify_gandson(){

		if(IS_GET){

			$map['id'] = I('get.id');
			$fid = I('get.fid');
			$fname = I('get.fname');

			$DB = M('food_classify');

			$list = $DB->where($map)->find();
			$list['choose_html_text'] = htmlspecialchars_decode($list['choose_html_text']);
			$list['faq_html_text'] = htmlspecialchars_decode($list['faq_html_text']);

			$this->assign('list',$list);
			$this->assign('fid',$fid);
			$this->assign('fname',$fname);
			$this->display();
		}else{

			$map['id'] = I('post.id');
			$name = trim(I('post.name'));
			if(!empty($name)){
				$data['name'] = $name;
			}
			
			$name_tag = trim(I('post.name_tag'));
			if(!empty($name_tag)){
				$data['name_tag'] = $name_tag;
			}
			
			$data['state'] = I('post.state');
			$fname = I('post.fname');
			$fid = I('post.fid');
			$choose_html_text = I('post.choose_html_text');
			$faq_html_text = I('post.faq_html_text');
			if(!empty($choose_html_text)){
				$data['choose_html_text'] = $choose_html_text;
			}
			if(!empty($faq_html_text)){
				$data['faq_html_text'] = $faq_html_text;
			}
			$DB = M('food_classify');

			$re = $DB->where($map)->data($data)->save();

			if($re){

				$this->success('修改成功!',U('Admin/Product/classify_lists_grandson',array('id'=>$fid,'fname' => $fname)),1);
			}else{

				$this->error('修改失败!','',1);
			}
		}
	}


	/**
	 * ajax获取所有分类
	 */
	public function select_classify_ajax(){

		if(IS_AJAX){

			$classify_name = trim(I('post.classify_name'));
			if(empty($classify_name)){

				return false;
			}
			$classify_name = '%'.$classify_name.'%';
			$map['name'] = array('like',$classify_name);
			$map['pid'] = array('neq',0);
			$map['state'] = 1;
			$DB = M('food_classify');

			$list = $DB->where($map)->select();
			if(!empty($list)){

				echo json_encode($list);
			}
		}
	}



	/**上传第三方数据**/
    public function upload_third_party(){

        if(IS_POST){

            $upload_url = '';
            $geturl = './Uploads/'.$this->upload_excel($_FILES['third_data'],$upload_url);
            // echo $geturl; die;

            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            //要导入的xls文件，位于根目录下的Public文件夹
            $filename=$geturl;
            //创建PHPExcel对象，注意，不能少了\
            $PHPExcel=new \PHPExcel();
            //如果excel文件后缀名为.xls，导入这个类
            import("Org.Util.PHPExcel.Reader.Excel5");
            //如果excel文件后缀名为.xlsx，导入这下类
            //import("Org.Util.PHPExcel.Reader.Excel2007");
            //$PHPReader=new \PHPExcel_Reader_Excel2007();

            $PHPReader=new \PHPExcel_Reader_Excel5();
            //载入文件
            $PHPExcel=$PHPReader->load($filename);
            //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
            $currentSheet=$PHPExcel->getSheet(0);
            //获取总列数
            $allColumn=$currentSheet->getHighestColumn();
//            echo $allColumn."<br/>";
            //获取总行数
            $allRow=$currentSheet->getHighestRow();
//            echo $allRow."<br/>";
            //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
            for($currentRow=2;$currentRow<=$allRow;$currentRow++){
                //从哪列开始，A表示第一列
                for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
//                    echo $currentColumn."-";
                    //数据坐标
                    $address=$currentColumn.$currentRow;
                    //读取到的数据，保存到数组$arr中
                    $arr[$currentRow][$currentColumn]=$currentSheet->getCell($address)->getValue();
                }
            }
//             print_r($arr); die;
            $i = 0;
            $a = 0;
            foreach ($arr as $key => $value) {
                # code..
                
//                $data[$i]['control_no'] = $value['A'];
                $data[$i]['firm_name'] = $value['A'];
                $data[$i]['firm_address'] = $value['B'];
                $data[$i]['department_name'] = $value['C'];
                $data[$i]['location'] = $value['D'];
                $data[$i]['province'] = $value['E'];
                $data[$i]['city'] = $value['F'];
                $data[$i]['product_name'] = $value['G'];
                $data[$i]['short_product_name'] = $value['K'];
                
                
                $data[$i]['s_category'] = $value['H'];
                $data[$i]['b_category'] = $value['H'];
                $data[$i]['product_type'] = $value['I'];
                
                $data[$i]['brand'] = $value['J'];
                $data[$i]['product_model'] = $value['L'];
                
                $data[$i]['cdate'] = $value['M'];
                $data[$i]['qualified'] = $value['N'];
                $data[$i]['item_name'] = $value['P'];
                $data[$i]['item_category'] = $value['O'];
                $data[$i]['items'] = $value['O'];
                $data[$i]['check_result'] = $value['Q'];
                $data[$i]['standard'] = $value['R'];
                
                $data[$i]['barcode'] = $value['S'];
                $data[$i]['bulletin_code_num'] = $value['T'];
                $data[$i]['bulletin_code'] = $value['T'];
                $data[$i]['bctime'] = $value['U'];
                
                
                $data[$i]['check_items'] = $value['V'];
//                $data[$i]['batch_no'] = $value['W'];
                $data[$i]['batch_no'] = $value['M'];
//                $data[$i]['origin'] = $value['AA'];
                $data[$i]['origin'] = I("post.origin");
                
                $data[$i]['self_resource'] = $value['X'];
                
//                $data[$i]['institution'] = $value['AC'];
                $data[$i]['remark'] = $value['Y'];
//                $data[$i]['import_remark'] = $value['Z'];
                $data[$i]['import_remark'] =I("post.import_remark");
                
                
                $data[$i]['ctime'] = I('server.REQUEST_TIME');   
                $data[$i]['unique_code'] = I('server.REQUEST_TIME').$i;   
                
                
                $data2[$i]['name'] = $value['G'];
                $data2[$i]['brand'] = $value['J'];
                $data2[$i]['classify_name'] = $value['H'];
                $data2[$i]['remark'] = $value['Y'];
                $data2[$i]['ctime'] = I('server.REQUEST_TIME');
                $data2[$i]['barcode'] = $value['S'];
                $data2[$i]['shortname'] = $value['K'];
                $data2[$i]['specification'] = $value['L'];
                $data2[$i]['unique_code'] = I('server.REQUEST_TIME').$i;
                
                $i++;
                
                echo $value['M']."<br/>";
            }
//            
//            print_r($data2);
//            exit();

//            foreach ($arr as $key => $value) {
//                # code..
//                $data2[$a]['name'] = $value['M'].$value['H'];
//                $data2[$a]['brand'] = $value['M'];
//                $data2[$a]['classify_name'] = $value['J'];
//                $data2[$a]['remark'] = $value['AD'];
//                $data2[$a]['ctime'] = I('server.REQUEST_TIME');
//                $data2[$a]['barcode'] = $value['U'];
//                $data2[$a]['shortname'] = $value['H'];
//                $data2[$a]['specification'] = $value['L'];
//                $data2[$a]['unique_code'] = I('server.REQUEST_TIME').$a;
//      
//                $a++;
//            }

//             print_r($data); die;
            $DB_import_excel = M('third_party_product');
            // var_dump($DB_import_excel); die;
            $res = $DB_import_excel->addAll($data);
            if(!empty($res)){

            	$re = M('product_from_thirdparty')->addAll($data2);

                if($re){
//                	$this->success('导入成功!',U('Admin/Product/lists'),1);
                }else{
                	$this->error('导入失败!','',1);
                }
            }else{

                $this->error('导入失败!','',1);
            }

        }
    }

    /**
     * 单文件上传
     */
    public function upload_excel($file,$upload_url){    
        $upload = new \Think\Upload();// 实例化上传类    
        $upload->maxSize   =     3145728 ;// 设置附件上传大小    
        $upload->exts      =     array('xls');// 设置附件上传类型    
        $upload->savePath  =     $upload_url; // 设置附件上传目录    
        // 上传单个文件     
        $info   =   $upload->uploadOne($file);    
        if(!$info) {
            // 上传错误提示错误信息        
            $this->error($upload->getError());    
            }else{
            // 上传成功 获取上传文件信息         
            return $info['savepath'].$info['savename'];    
        }
    }




    /**
     * 后台产品用户纠错反馈管理
     */
    public function feedback_product(){

    	if(IS_POST){

    	}else{

    		$isbeen = I('get.isbeen');

    		$User=M('feedback_product_error');
			/**
			数据分页显示开始
			**/
			$count      = $User->where(array('isbeen' => $isbeen))->count();// 查询满足要求的总记录数
			$Page       = new \Think\Page($count,40);// 实例化分页类 传入总记录数和每页显示的记录数(25)
			$Page->lastSuffix=false;
		    $Page->setConfig('header','<li class="rows">共<b>%TOTAL_ROW%</b>条记录&nbsp;&nbsp;每页<b>40</b>条&nbsp;&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
		    $Page->setConfig('prev','上一页');
		    $Page->setConfig('next','下一页');
		    $Page->setConfig('last','末页');
		    $Page->setConfig('first','首页');
		    $Page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
			$show       = $Page->show();// 分页显示输出
			// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
			$list = $User->where(array('isbeen' => $isbeen))->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
			/**j
			数据分页结束upload_third_party
			**/
			$DB_1 = M('members');
			$DB_2 = M('fundings_image');
			foreach ($list as $key => $value) {
				# code...
				$list[$key]['username'] = $DB_1->where(array('id' => $value['mid']))->getField('username');
				$list[$key]['image'] = $DB_2->where(array('id' => $value['img_id']))->getField('img_url');
			}

			$this->assign('show',$show);
			$this->assign('list',$list);
    		$this->display();
    	}
    }



    /**
     * 处理纠错反馈
     */
    public function solve_feedback_product(){

    	$DB = M('feedback_product_error');
    	$data['isbeen'] = 1;
    	$map['id'] = I('post.id');

    	$re = $DB->where($map)->data($data)->save();

    	if(!empty($re)){

    		echo json_encode(1);
    	}else{

    		echo json_encode(0);
    	}
    }
}
